package br.ufc.database.util;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;

public class JPAUtil {

	private static final EntityManagerFactory emf = createEMF();
	private static ThreadLocal<EntityManager> ems = new ThreadLocal<>();

	public static EntityManager openEntityManager() {
		EntityManager em = ems.get();

		if (em == null) {
			em = emf.createEntityManager();
			ems.set(em);
		}

		return em;
	}

	private static EntityManagerFactory createEMF() {
		try {
			Class.forName("org.postgresql.Driver");
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return Persistence.createEntityManagerFactory("banco_quero_teto");
		
	}

	public static void close() {

		EntityManager em = ems.get();
		if (em != null) {
			if (em.getTransaction().isActive()) {
				em.getTransaction().rollback();
			}
			em.close();
			ems.set(null);
		}
	}

	public static void beginTransaction() {
		openEntityManager().getTransaction().begin();
	}

	public static void commit() {
		EntityTransaction tx = openEntityManager().getTransaction();
		if (tx.isActive()) {
			tx.commit();
		}
	}

	public static void rollback() {
		EntityTransaction tx = openEntityManager().getTransaction();
		if (tx.isActive()) {
			tx.rollback();
		}
	}
}
